package com.rzico.sbl.ui.report

import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.isVisible
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportDriverDepotBinding
import com.rzico.sbl.model.DepotOutData
import com.rzico.sbl.other.serviceStep
import com.rzico.sbl.ui.report.depot.ReportDepotEditActivity
import com.rzico.sbl.ui.report.depot.ReportDepotOrderActivity
import com.rzico.sbl.ui.report.depot.ReportDepotViewActivity
import com.rzico.sbl.ui.report.dispatch.ReportDispatchFirstActivity
import com.rzico.sbl.ui.report.dispatch.ReportEndFirstActivity
import com.rzico.sbl.ui.report.other.goToOrderDetail
import com.rzico.sbl.viewmodel.ReportDepotViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.bottomHide
import com.xinnuo.common.helper.bottomShow
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common.helper.intValue
import com.xinnuo.common.listener.onTabSelectedListener
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.utils.addOnScrollChanged
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.showActionDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter

class ReportDriverDepotActivity : BaseActivity(R.layout.activity_report_driver_depot) {

    private val mBinding by lazy { ActivityReportDriverDepotBinding.bind(getRootView()) }

    private var mStatus = ""

    override fun getViewModel() = get<ReportDepotViewModel>()

    override fun initData() {
        initTitle(title = "出入库")

        initLayout()
        initTabLayout()
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout.also {
                    it.emptyHint.text = "暂无相关合并单信息！"
                }

                recycleList.also { view ->
                    view.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = {
                            when (mStatus) {
                                "unconfirmed" -> getOutData(0)
                                else -> getInData(0)
                            }
                        },
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    when (mStatus) {
                                        "unconfirmed" -> getOutData(pageNum)
                                        else -> getInData(pageNum)
                                    }
                                }
                        }
                    )

                    view.addItemDecoration(SpaceTBDecoration(hasHeader = false, bottom = 65f))
                    view.addOnScrollChanged(
                        onShow = { mBinding.depotBottom.bottomShow() },
                        onHide = { mBinding.depotBottom.bottomHide(52f) }
                    )
                }
            }
    }

    /**
     * 出库适配器
     */
    private fun initOutAdapter() {
        mBinding
            .listLayout
            .emptyLayout
            .emptyHint
            .text = "暂无合并单信息\n请点击添加出库生成合并单！"

        mAdapter = SlimAdapter.creator()
            .register<DepotOutData>(R.layout.item_report_depot_out) { jector, bean, _ ->
                jector.apply {
                    gone(R.id.item_depot_btn2)
                    text(R.id.item_depot_name, bean.name)
                    text(R.id.item_depot_btn1, "修改")
                    text(
                        R.id.item_depot_time,
                        "创建时间: ${bean.createDate.getTimeString()}"
                    )
                    text(
                        R.id.item_depot_total,
                        bean.productList.sumOf { it.quantity.intValue }.toString()
                    )

                    with<LinearLayout>(R.id.item_depot_content) { layout ->
                        layout.removeAllViews()

                        bean.productList.forEach {
                            layout.addView(
                                inflate<View>(R.layout.content_report_depot_hint).apply {
                                    find<TextView>(R.id.conent_title).text = it.name
                                    find<TextView>(R.id.conent_num).text = it.quantity
                                }
                            )
                        }
                    }

                    with<LinearLayout>(R.id.item_depot_sn) { layout ->
                        layout.removeAllViews()

                        bean.snList.forEach { item ->
                            layout.addView(
                                inflate<View>(R.layout.content_report_depot_station_title).apply {
                                    find<TextView>(R.id.conent_title).apply {
                                        text = "${item.name}(${item.sn})："

                                        oneClick {
                                            goToOrderDetail("orderSn" to item.sn)
                                        }
                                    }
                                }
                            )

                            item.itemList.forEach {
                                layout.addView(
                                    inflate<View>(R.layout.content_report_depot_hint).apply {
                                        find<View>(R.id.conent_space).visible = true
                                        find<TextView>(R.id.conent_title).text = it.name
                                        find<TextView>(R.id.conent_num).text = it.quantity
                                    }
                                )
                            }
                        }
                    }

                    clicked(R.id.item_depot_btn1) {
                        startActivityEx<ReportDepotOrderActivity>(
                            "memberId" to bean.seller,
                            "groupId" to bean.id,
                            "orderSn" to bean.snList.joinToString(",")
                        )
                    }
                }
            }
            .attachTo(mBinding.listLayout.recycleList)
    }

    /**
     * 入库适配器
     */
    private fun initInAdapter() {
        mBinding
            .listLayout
            .emptyLayout
            .emptyHint
            .text = "暂无相关合并单信息！"

        mAdapter = SlimAdapter.creator()
            .register<DepotOutData>(R.layout.item_report_driver_depot) { jector, bean, _ ->
                jector.apply {
                    text(
                        R.id.item_depot_time,
                        when (mStatus) {
                            "debit" -> "出库时间: ${bean.debitDate.getTimeString()}"
                            else -> "入库时间: ${bean.creditDate.getTimeString()}"
                        }
                    )
                    text(R.id.item_depot_memo, bean.memo)

                    visibility(
                        R.id.item_depot_bottom,
                        visibleValue {
                            mStatus == "debit"
                                    && bean.snList.any { !it.shippingId.isNullOrEmpty() }
                        }
                    )
                    visibility(
                        R.id.item_depot_checking,
                        visibleValue { bean.status == "4" }
                    )
                    visibility(
                        R.id.item_depot_btn,
                        visibleValue { bean.status != "4" }
                    )
                    visibility(
                        R.id.item_depot_memo_ll,
                        invisibleValue { mStatus != "debit" || bean.memo.isNullOrEmpty() }
                    )

                    with<LinearLayout>(R.id.item_depot_sn) { layout ->
                        layout.removeAllViews()

                        bean.snList.forEach { item ->
                            layout.addView(
                                inflate<View>(R.layout.content_report_driver_depot).apply {
                                    find<TextView>(R.id.conent_title).apply {
                                        text = "${item.sn}(${item.name})"

                                        oneClick {
                                            goToOrderDetail("orderSn" to item.sn)
                                        }
                                    }
                                    find<TextView>(R.id.conent_edit).apply {
                                        isVisible = serviceStep != "1"
                                                && bean.status != "4"
                                                && mStatus == "debit"
                                                && item.status == "已送达"

                                        oneClick {
                                            startActivityEx<ReportEndFirstActivity>(
                                                "shipId" to item.shippingId,
                                                "orderSn" to item.sn,
                                                "shippingSn" to item.shippingSn
                                            )
                                        }
                                    }
                                    find<TextView>(R.id.conent_status)
                                        .apply {
                                            isVisible = item.status == "未送达"

                                            if (item.shippingId.isNullOrEmpty())
                                                text = "未发货"
                                        }
                                }
                            )
                        }
                    }

                    with<TextView>(R.id.item_depot_btn) { tvHint ->
                        tvHint.text =
                            conditionIf(
                                bean.snList.none { it.status == "未送达" },
                                "空桶入库",
                                "订单送达"
                            )

                        tvHint.oneClick {
                            if (bean.snList.none { it.status == "未送达" }) {
                                startActivityEx<ReportDepotEditActivity>(
                                    "groupId" to bean.id
                                )
                            } else {
                                val itemList = bean.snList.filter { it.status == "未送达" }
                                val itemArray =
                                    itemList.map { "${it.sn}(${it.name})" }
                                        .toTypedArray()

                                showActionDialog(
                                    items = itemArray
                                ) { index, _ ->
                                    val shippingId = itemList[index].shippingId ?: ""
                                    val shippingSn = itemList[index].shippingSn ?: ""

                                    (shippingId.isEmpty()
                                            || shippingSn.isEmpty())
                                        .conditionElse(
                                            actionTrue = { showToast("请确认该订单已发货") },
                                            actionFalse = {
                                                startActivityEx<ReportDispatchFirstActivity>(
                                                    "shipId" to itemList[index].shippingId,
                                                    "orderSn" to itemList[index].sn,
                                                    "shippingSn" to itemList[index].shippingSn
                                                )
                                            }
                                        )
                                }
                            }
                        }
                    }

                    clicked {
                        startActivityEx<ReportDepotViewActivity>(
                            "groupId" to bean.id
                        )
                    }
                }
            }
            .attachTo(mBinding.listLayout.recycleList)
    }

    /**
     * 初始化 TabLayout
     */
    private fun initTabLayout() {
        mBinding
            .depotTab
            .apply {
                onTabSelectedListener {
                    onTabSelected {
                        it?.let {
                            mStatus = when (it.position) {
                                0 -> "unconfirmed"
                                1 -> "debit"
                                2 -> "credit"
                                else -> ""
                            }

                            mBinding
                                .depotBottom
                                .isVisible = mStatus == "unconfirmed"

                            when (mStatus) {
                                "unconfirmed" -> initOutAdapter()
                                else -> initInAdapter()
                            }

                            getViewModel().cancelRequest()
                            getViewModel().delay { updateList() }
                        }
                    }
                }

                addTab(this.newTab().setText("待出库"), false)
                addTab(this.newTab().setText("待入库"), true)
                addTab(this.newTab().setText("已入库"), false)
            }
    }

    override fun initListener() {
        mBinding.apply {
            btAdd.oneClick { startActivityEx<ReportDepotOrderActivity>() }
        }

        observe<String>("depotOutList") { updateList() }
        observe<String>("deliverModify") { updateList() }
    }

    /**
     * 司机出库合并单列表
     */
    private fun getOutData(index: Int) {
        getViewModel()
            .outList(
                page = index,
                status = mStatus,
                onSuccess = {
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 司机入库合并单列表
     */
    private fun getInData(index: Int) {
        getViewModel()
            .inList(
                page = index,
                status = mStatus,
                onSuccess = {
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        when (mStatus) {
            "unconfirmed" -> getOutData(0)
            else -> getInData(0)
        }
    }

    override fun onResume() {
        super.onResume()

        getViewModel()
            .orderCount()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = {
                    mBinding
                        .depotCount
                        .setBadgeCount(it.intValue)
                }
            )
    }

}